package com.itbupt.trigger.listener;

import com.alibaba.fastjson2.TypeReference;
import com.alibaba.fastjson2.JSON;
import com.itbupt.domain.activity.service.IRaffleActivitySkuStockService;
import com.itbupt.types.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author dingchang
 * @Date 2025/3/31 16:03
 * @Description: 活动sku库存耗尽 - 监听处理
 * 监听MQ消息， 处理库存为0时，清空延迟队列
 */

@Slf4j
@Component
public class ActivitySkuStockZeroCustomer {

    @Value("${spring.rabbitmq.topic.activity_sku_stock_zero}")
    private String topic;

    @Resource
    private IRaffleActivitySkuStockService skuStock;

    // @RabbitListener：监听指定的RabbitMQ队列（activity_sku_stock_zero），队列不存在时会自动创建。
    @RabbitListener(queuesToDeclare = @Queue(value = "activity_sku_stock_zero"))
    public void listener(String message) {
        try {
            log.info("监听活动sku库存消耗为0消息 topic: {} message: {}", topic, message);

            // 转换对象 - JSON格式转换为 EventMessage<Long> 对象
            BaseEvent.EventMessage<Long> eventMessage = JSON.parseObject(
                    message,
                    new TypeReference<BaseEvent.EventMessage<Long>>() {}.getType());

            // 解析消息中的sku
            Long sku = eventMessage.getData();

            // 更新库存 - 清空活动sku库存 - 落库
            skuStock.clearActivitySkuStock(sku);

            // 清空延迟队列 - 此时就不需要延迟更新数据库记录了
            // skuStock.clearQueueValue();

        } catch (Exception e) {
            log.error("监听活动sku库存消耗为0消息，消费失败 topic: {} message: {}", topic, message);
            throw e;
        }
    }


}
